package com.ayanami.userservice.controller;


import com.ayanami.basecommon.exception.BusinessException;
import com.ayanami.osscommon.utils.AliOSSUtils;
import com.ayanami.userservice.entity.TbUser;
import com.ayanami.userservice.service.TbUserService;
import com.ayanami.userservice.vo.TbUserVO;
import com.ayanami.utilscommon.response.Result;
import com.ayanami.utilscommon.util.MD5Utils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author ayanami
 * @since 2020-07-20
 */
@Api("用户管理")
@RestController
@RequestMapping("/userservice/tb-user")
@CrossOrigin
public class TbUserController {
    @Autowired
    private TbUserService tbUserService;
    @ApiOperation(value = "查询全部",notes = "用户")
    @GetMapping("/users")
    public Result users(){
        System.out.println(UUID.randomUUID().toString().substring(0, 32));
        List<TbUser> list = tbUserService.list(null);
        Result users = Result.ok().data("users", list);
        return users;
    }
    @ApiOperation(value = "分页查询",notes = "获取分页对象")
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(required = false,defaultValue = "1")Integer current,@RequestParam(required = false,defaultValue = "5")Integer pageSize){
        Page<TbUser> page=new Page<>(current,pageSize);
        QueryWrapper<TbUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.ne("deleted",1);
        page=tbUserService.page(page,queryWrapper);
        long total=page.getTotal();
        List<TbUser> list=page.getRecords();
        return Result.ok().data("total",total).data("users",list);
    }
    @ApiOperation(value = "根据id删除",notes = "逻辑删除用户")
    @DeleteMapping("/delusers")
    public Result delUser(Integer id){
        boolean b = tbUserService.removeById(id);
        if(b) {
            return Result.ok().message("删除成功");
        }else{
            return Result.error().message("失败");
        }
    }
    @ApiOperation(value = "分页查询",notes = "获取分页对象")
    @GetMapping("/findByPage")
    public Result findByPage(@RequestParam(required = false,defaultValue = "1")Integer current, @RequestParam(required = false,defaultValue = "5")Integer pageSize,TbUserVO tbUserVO){
        Page<TbUser> page=new Page<>(current,pageSize);
        QueryWrapper<TbUser> queryWrapper =new QueryWrapper<>();
        if(StringUtils.isNotEmpty(tbUserVO.getUsername())) {
            queryWrapper.like("username", tbUserVO.getUsername());
        }
        if(tbUserVO.getDepartmentId()!=null) {
            queryWrapper.eq("department_id", tbUserVO.getDepartmentId());
        }
        if(StringUtils.isNotEmpty(tbUserVO.getEmail())) {
            queryWrapper.like("email", tbUserVO.getEmail());
        }
        if(StringUtils.isNotEmpty(tbUserVO.getNickname())) {
            queryWrapper.like("nickname", tbUserVO.getNickname());
        }
        if(tbUserVO.getSex()!=null){
            queryWrapper.eq("sex",tbUserVO.getSex());
        }
        queryWrapper.eq("tb_user.deleted",0);
        IPage<TbUser> userAndDept = tbUserService.findUserAndDept(page, queryWrapper);
        if(userAndDept!=null) {
            long total=userAndDept.getTotal();
            List<TbUser> list=userAndDept.getRecords();
            return Result.ok().data("total", total).data("users", list).data("page",userAndDept);
        }else{
            return Result.error().message("错误，请重试");
        }
    }
    @ApiOperation(value = "根据账户密码登录",notes = "返回用户信息")
    @PostMapping("/login")
    public Result login(String username,String password){
        if(StringUtils.isNotEmpty(username)&&StringUtils.isNotEmpty(password)){
            QueryWrapper<TbUser> dd=new QueryWrapper<>();
            dd.eq("username",username);
            TbUser one1 = tbUserService.getOne(dd);
            if(one1!=null) {
                password = MD5Utils.md5Encryption(password, one1.getSalt());
            }else{
                throw new BusinessException(20001,"找不到此用户名");
            }
            QueryWrapper<TbUser> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("username",username);
            queryWrapper.eq("password",password);
            TbUser one = tbUserService.getOne(queryWrapper);
            if(one!=null) {
                return Result.ok().data("user", one);
            }else{
                return Result.error().message("账号或密码错误");
            }
        }else {
            return Result.error().message("账号密码为空,I`s so fucking craze!");
         }
    }
    @ApiOperation(value = "新增用户",notes = "true/false")
    @PostMapping("addUser")
    public Result addUser(@RequestBody TbUser tbUser){
        if(tbUser!=null) {
            tbUser.setStatus(1);
            tbUser.setSalt(UUID.randomUUID().toString().substring(0, 32));
            tbUser.setType(1);
            tbUser.setPassword(MD5Utils.md5Encryption(tbUser.getPassword(), tbUser.getSalt()));
            tbUser.setDeleted(0);
            boolean save = tbUserService.save(tbUser);
            if (save) {
                return Result.ok().message("成功");
            } else {
                return Result.error().message("失败");
            }
        }else{
            return Result.error().message("意外故障");
        }
    }
    @ApiOperation(value = "修改用户",notes ="true/false")
    @PutMapping("/updUser")
    public Result updUser(@RequestBody TbUser tbUser){
        tbUser.setSalt(UUID.randomUUID().toString().substring(0,32));
        tbUser.setPassword(MD5Utils.md5Encryption(tbUser.getPassword(),tbUser.getSalt()));
        boolean updateById = tbUserService.updateById(tbUser);
        if(updateById){
            return Result.ok().message("修改成功");
        }else {
            return Result.error().message("修改失败");
        }
    }
    @ApiOperation(value = "根据id查询",notes = "id")
    @GetMapping("/findById")
    public Result findById(Integer Id){
        TbUser byId = tbUserService.getById(Id);
        if(byId!=null) {
            return Result.ok().data("user", byId);
        }else{
           throw new BusinessException(20001,"用户不存在");
        }
    }
    @ApiOperation(value = "导出用户信息",notes = "导出")
    @PostMapping("/export")
    public void exportTbUserInfoExcel(HttpServletResponse response,@RequestBody(required = false) TbUserVO tbUserVO) throws IOException {
        tbUserService.exportUserInfoExcel(response,tbUserVO);
    }
    @ApiOperation(value = "头像修改",notes = "头像")
    @PostMapping("/uploadImg/{name}")
    public Result uploadImg(MultipartFile file, @PathVariable("name")String name){
        AliOSSUtils aliOSSUtils=new AliOSSUtils();
        String avatar=aliOSSUtils.upload(file);
        UpdateWrapper<TbUser> wrapper=new UpdateWrapper<>();
        wrapper.set("avatar",avatar);
        wrapper.eq("username",name);
        return tbUserService.update(wrapper)?Result.ok().data("avatar",avatar):Result.error();
    }
    @ApiOperation(value = "根据用户名获取头像地址",notes = "")
    @GetMapping("/findByUserName")
    public Result findByUserName(String username){
        QueryWrapper<TbUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        TbUser one = tbUserService.getOne(queryWrapper);
        return one!=null?Result.ok().data("avatar",one.getAvatar()):Result.error();
    }
}

